<template>
  <section class="component module-permission">
    <div class="row">
      <div class="resource-tree">
        <common-title title="菜单资源"></common-title>
        <resource-tree
          v-model="checkedMenuIds"
          ref="resource-tree"
          :cureentKey.sync="currentTreeKey"
        ></resource-tree>
      </div>
      <div class="col-span">
        <common-title title="按钮资源"></common-title>
        <resource-control
          v-model="controlCheckedIds"
          :currentTreeId="currentTreeKey"
          @check-tree-node="onCheckTreeNodeChange"
        ></resource-control>
      </div>
    </div>
    <div class="operate-buttons">
      <el-button class="cancel-button" @click="emitClose">取消</el-button>
      <el-button @click="saveModule">保存</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import { Tree } from "element-ui";
import Component from "vue-class-component";
import DataForm from "~/components/common/data-form.vue";
import DataBox from "~/components/common/data-box.vue";
import { Dependencies } from "~/core/decorator";
import { RoleService } from "~/services/management-service/role.service";
import { CommonService } from "~/utils/common.service";
import { Emit, Watch, Prop } from "vue-property-decorator";
import { namespace } from "vuex-class";
import ResourceTree from "./resource-tree.vue";
import ResourceControl from "./resource-control.vue";
import CommonTitle from "~/components/common/common-title.vue";

const systemModule = namespace("system-manage");

@Component({
  components: {
    ResourceTree,
    ResourceControl,
    CommonTitle
  }
})
export default class ModulePermission extends Vue {
  @Dependencies(RoleService) private roleService: RoleService;
  @systemModule.Getter private systemControls: any[];
  @systemModule.Getter private systemMenus: any[];

  private checkedMenuIds: string[] = [];
  private controlCheckedIds: string[] = [];
  private controlDataSet: any[] = [];
  private currentTreeKey: string = "";
  private treeData: any = [];

  @Prop({ required: true })
  private roleId: string;

  @Emit("refreshList")
  private refreshList() {}

  @Watch("roleId", { immediate: true })
  private onRoleIdChange(val) {
    if (!val) return;
    this.refreshDate();
  }

  @Watch("checkedMenuIds")
  private onCheckedMenuIdsChange(values: number[], oldVlaues: number[]) {
    const oldCheckedControls = [...this.controlCheckedIds];
    // 处理增加的
    const addKeys = values.filter(x => !oldVlaues.includes(x));
    addKeys.forEach(v => {
      const addControls = this.systemControls
        .filter(x => x.parent === v)
        .map(v => v.id);
      oldCheckedControls.push(...addControls);
    });
    const checkedControlSet = new Set(oldCheckedControls);
    // 处理减少的
    const unCheckMenuIds = oldVlaues.filter(x => !values.includes(x));
    unCheckMenuIds.forEach(v => {
      const removeControls = this.systemControls.filter(x => x.parent === v);
      removeControls.forEach(c => checkedControlSet.delete(c.id));
    });
    this.controlCheckedIds = Array.from(checkedControlSet);
    const oldCurrentTreeKey = this.currentTreeKey;
    this.currentTreeKey = "";
    this.$nextTick(() => {
      this.currentTreeKey = oldCurrentTreeKey;
    });
  }

  @Emit("close")
  private emitClose() {
    this.refreshDate();
  }

  private getAllTreeData() {
    const option = {
      keyName: "id",
      parentKeyName: "parent",
      sortKey: "resoSort"
    };

    return CommonService.generateTreeData(this.systemMenus, option);
  }

  private getRoleTreeData(data) {
    const option = {
      keyName: "id",
      parentKeyName: "parent",
      sortKey: "resoSort"
    };
    return this.$common.generateTreeData(data, option);
  }

  private refreshDate() {
    if (!this.roleId) return;
    // 全部菜单数据
    this.treeData = this.getAllTreeData();
    this.roleService.getSelfResources(this.roleId).subscribe(data => {
      this.checkedMenuIds = data
        .filter(x => x.type !== "CONTROL")
        .map(x => x.id);
      this.controlCheckedIds = data
        .filter(x => x.type === "CONTROL")
        .map(x => x.id);
      // 用户权限菜单数据
      const tree = this.getRoleTreeData(data);
      // 当菜单的子级没有全部选择时，去掉父级的ID，避免选中父级
      tree.forEach(v => {
        const obj = this.treeData.find(i => i.id === v.id);
        if (
          !!obj &&
          obj.children &&
          obj.children.length !== v.children.length
        ) {
          const index = this.checkedMenuIds.findIndex(c => c === v.id);
          this.checkedMenuIds.splice(index, 1);
        }
      });
    });
  }

  private onCheckTreeNodeChange() {
    if (this.checkedMenuIds.includes(this.currentTreeKey)) return;
    this.checkedMenuIds.push(this.currentTreeKey);
  }

  private saveModule() {
    const treeresource: any = this.$refs["resource-tree"];
    const checkedResults = [
      ...treeresource.getCheckedNodes(),
      ...this.controlCheckedIds
    ];
    console.log(checkedResults)
    this.roleService
      .roleAttachResource(this.roleId, checkedResults)
      .subscribe(data => {
        this.$message.success("操作成功!");
        this.emitClose();
      });
  }
}
</script>

<style lang="less" scoped>
.component.module-permission {
  .resource-tree {
    flex-basis: 250px;
  }
  .common-title {
    background-color: #e4e4e4;
  }
}
</style>
